package me.android.library.utils.android;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.PowerManager;
import android.provider.Settings;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@UtilityClass
public class PowerUtil {

    /**
     * 需要权限：  <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
     */
    @SuppressLint("BatteryLife")
    public void addWhileIdle() {
        if (!isIgnoringBatteryOptimizations()) {
            Context cx = ContextUtil.getAppContext();
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + cx.getPackageName()));
            cx.startActivity(intent);
        }
    }

    public void callIgnoreBatteryOptimizationSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
        ContextUtil.getAppContext().startActivity(intent);
    }

    public boolean isIgnoringBatteryOptimizations() {
        String packageName = ContextUtil.getAppContext().getPackageName();
        PowerManager pm = SystemServiceUtil.getPowerManager();
        return pm.isIgnoringBatteryOptimizations(packageName);
    }
}
